package com.sunb2b.web.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.inject.Inject;
import javax.validation.Valid;

import org.apache.lucene.queryParser.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sunb2b.entity.Product;
import com.sunb2b.pojo.SearchResult;
import com.sunb2b.service.SearchEngine;
import com.sunb2b.web.form.SearchCriteria;

@Controller
public class SearchController {
    @Inject
    private SearchEngine searchEngine;
    
    @RequestMapping(value="/admin/search/preUpdateIndex", method=RequestMethod.GET)
    public String preCreateIndex(Model model) throws IOException{
        return "/admin/search/updateIndex";
    }
   
    @RequestMapping(value="/admin/search/updateIndex", method=RequestMethod.GET)
    public String updateIndex(Model model) throws IOException{
        searchEngine.updateIndex();
        String message = "Form submitted successfully.";
        model.addAttribute("message", message);
        return null;
    }

    @RequestMapping(value="/search", method=RequestMethod.GET)
    public String preSearch(@Valid SearchCriteria searchCriteria, Model model) throws IOException, ParseException{
        searchCriteria.setCategoryId("100");
        searchCriteria.setRegionId("100");
        searchCriteria.setPageSize(10);
        //searchCriteria.setPage(1);
        SearchResult sr = searchEngine.search(searchCriteria);
        List<Product> products = sr.getResults();
        model.addAttribute("total", sr.getTotalHits());
        model.addAttribute("searchCriteria", searchCriteria);
        model.addAttribute("products", products);
        model.addAttribute("page", searchCriteria.getPage());
        return null;
    }
   
    @RequestMapping(value="/search", method=RequestMethod.POST)
    public String search(@Valid SearchCriteria searchCriteria, Model model) throws IOException, ParseException{
    	SearchResult sr = searchEngine.search(searchCriteria);
        List<Product> products = sr.getResults();
        model.addAttribute("searchCriteria", searchCriteria);
        model.addAttribute("products", products);
        model.addAttribute("total", sr.getTotalHits());
        model.addAttribute("page", 1);
        
        return null;
    }
}



